import { useRef, useImperativeHandle, forwardRef, Ref } from 'react'
import { useEnter } from '../../utils/hooks'
import { createEditor, createToolbar, IDomEditor, IEditorConfig, IToolbarConfig, Toolbar } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'
import './style.less'

type EditorProps = {
  editorConfig?: Partial<IEditorConfig>
  toolbarConfig?: Partial<IToolbarConfig>
  height?: number
}

export type RefProps = {
  editor: IDomEditor | null,
  toolbar: Toolbar | null
}
/**
 * https://www.wangeditor.com/v5/getting-started.html
 */
function Editor ({
  editorConfig = {},
  toolbarConfig = {},
  height = 500
}: EditorProps, ref: Ref<RefProps>) {
  const editorDom = useRef(null)
  const editorRef = useRef<IDomEditor | null>(null)
  const toolbarDom = useRef(null)
  const toolbarRef = useRef<Toolbar | null>(null)

  useEnter(() => {
    const editor = createEditor({
        selector: editorDom.current as unknown as HTMLElement,
        html: '<p><br></p>',
        config: {
          placeholder: '请输入内容',
          ...editorConfig
        },
        mode: 'default'
    })
    editorRef.current = editor
    const toolbar = createToolbar({
        editor,
        selector: toolbarDom.current as unknown as HTMLElement,
        config: {
          ...toolbarConfig
        },
        mode: 'default'
    })
    toolbarRef.current = toolbar
  })

  useImperativeHandle(ref, () => ({
    editor: editorRef.current,
    toolbar: toolbarRef.current
  }))

  return (
    <div className="editor-wrapper">
      <div className="editor-toolbar" ref={toolbarDom}></div>
      <div className="editor-content" ref={editorDom} style={{
        height
      }}></div>
    </div>
  )
}

export default forwardRef(Editor)
